{TokenType} = require "./tokenType"
{Token} = require "./token"
{RefreshResult} = require './RefreshResult'
Uuid = require "node-uuid"
class Refresh
  constructor: (@apiKeyRepository, @tokenRepository, @entrustProxy) ->

  validateApiKey: (apiKeyId, callback) ->
    @apiKeyRepository.get apiKeyId, (err, apiKey)->
      if (apiKey?)
        return callback(null, true)
      return callback(null, false)

  validateToken: (tokenId, callback) ->
    @tokenRepository.get tokenId, (err, token) ->
      currentDate = Date.now()
      if (token?.TokenExpiration >= currentDate)
        if (token.TokenType is TokenType.Refresh)
          return callback(null, token.UserId)
      return callback(null, null)


  isUserLockedOrSuspended: (userName) ->
    @entrustProxy.isUserLocked(userName) or @entrustProxy.isUserSuspended(userName)

  createAndStoreAccessToken: (userId, expirationDate, callback) ->
    token = new Token()
    token.UerId = userId
    token.Expiration = expirationDate
    token.Type = TokenType.Access
    token.Id = Uuid.v1()
    @tokenRepository.set token.Id, token, (err)->
      return callback null, token

  refresh: (refreshRequest, callback) ->
    tokenId = refreshRequest.RefreshToken
    apiKeyId = refreshRequest.ApiKey
    @validateToken tokenId, (err, userId) =>
      @validateApiKey apiKeyId, (err, isValid) =>
        if (isValid)
          expireDate = new Date()
          expireDate.setDate( expireDate.getDate() + 1)
          @createAndStoreAccessToken userId, expireDate.toISOString(), (err, accessToken)->
            refreshResult = new RefreshResult()
            refreshResult.AccessToken = accessToken.Id
            refreshResult.AccessTokenExpiration = accessToken.Expiration
            return callback null, refreshResult
        else
          return callback new Error "Invalid Api Key"

#  requestRefresh: (refreshRequest)->
#    @refresh refreshRequest.RefreshToken, refreshRequest.ApiKey

root = exports ? window
root.Refresh = Refresh
